// http://expressjs.com/
const express = require("express");
const { createServer } = require("http");
// https://socket.io/
const { Server } = require("socket.io");
// https://github.com/socketio/socket.io-admin-ui/
const { instrument } = require("@socket.io/admin-ui");
// https://www.npmjs.com/package/redis/v/3.1.2
const { createClient } = require('redis');
// https://github.com/socketio/socket.io-redis-adapter
const { createAdapter } = require('@socket.io/redis-adapter');
// https://github.com/socketio/socket.io-redis-emitter
const { Emitter } = require("@socket.io/redis-emitter");


const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
    cors: {
        // origin: "*",
        origin: ["https://admin.socket.io"],
        methods: ["GET", "POST"],
        allowedHeaders: ["my-custom-header"],
        credentials: true
    }
});

const pubClient = createClient({ host: '127.0.0.1', port: 6379 });
const subClient = pubClient.duplicate();

io.adapter(createAdapter(pubClient, subClient));

// https://admin.socket.io/#/
instrument(io, {
    auth: false
});

io.on("connection", (socket) => {
    // console.log(socket);

    console.log(`connect ${socket.id}`);

    socket.join("room42");

    socket.emit("data", "hello world.");
    socket.broadcast.emit('data', 'to all clients except sender');
    socket.to('room42').emit('data', "to all clients in 'room42' room except sender");

    socket.on("data", (arg) => {
        console.log(`client data: ${arg}`);
    });

    socket.on("disconnect", (reason) => {
        console.log(`disconnect ${socket.id} due to ${reason}`);
    });

    io.emit('data', 'to all clients');
    io.to('room42').emit('data', "to all clients in 'room42' room");

});

httpServer.listen(3000);

app.get('/', function (req, res) {

    const redisClient = createClient();
    const emitter = new Emitter(redisClient);

    emitter.emit("data", new Date);

    res.send('ok!')
})